package com.teacher.hong.service.impl;

import com.teacher.hong.dao.ClazzDao;
import com.teacher.hong.dao.StudentDao;
import com.teacher.hong.entity.Clazz;
import com.teacher.hong.service.IClazzService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;

/**
 * 班级服务实现类
 */
@Service("clazzService")
public class ClazzServiceImpl implements IClazzService {

    @Resource
    ClazzDao clazzDao;
    StudentDao studentDao;

//    public void setClazzDao(ClazzDao clazzDao) {
//        this.clazzDao = clazzDao;
//        System.out.println("执行ClazzServiceImpl的setClazzDao函数..");
//    }

    @Resource
    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }

    @Override
    public List<Clazz> list() {
        try {
            return clazzDao.select();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean save(Clazz clazz) {
        try {
            if (clazz.getId() != 0 && clazzDao.selectCountById(clazz.getId()) == 0) {
                System.out.println("该班ID不存在");
                return false;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (clazzDao.selectCountByName(clazz.getName()) > 0) {
                System.out.println("该班级名称已存在");
                return false;
            } else {
                return clazz.getId() == 0 ? clazzDao.insert(clazz) > 0 : clazzDao.update(clazz) > 0;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return false;
        }
    }

    public boolean remove(int id) {
        try {
            if (clazzDao.selectCountById(id) == 0) {
                System.out.println("该班ID不存在");
                return false;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (studentDao.selectCountByClazzId(id) > 0) {
                System.out.println("有关联的学生数据");
                return false;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            return clazzDao.delete(id) > 0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return false;
        }
    }

}
